<template>
  <Table filter v-bind="tableOpts" v-on="tableEvent" :key="componentKey">
    <template #operator>
      <div class="operator-wrap">
        <modifyInventory ref="dialogRef" @change="fetchCurrentTable" />
        <div style="display: flex">
          <el-upload
            :show-file-list="false"
            :headers="headers"
            :action="`${$apiHost}/material/inventory/import/execl`"
            :on-success="onSuccess"
            :on-error="onError"
            :before-upload="onBefore"
          >
            <el-button size="small" type="primary">
              导入库存
              <span v-if="loading" class="el-icon-loading"></span>
            </el-button>
          </el-upload>
          <el-dropdown @command="defaultInventory">
            <el-button type="primary" size="small" style="margin-left: 10px">
              导出库存<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="item in areaList" v-model="item.area" :command="item.area" :key="item.area">
                {{ item.areaName }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <el-dialog
        title="修改库位"
        :visible.sync="openWare"
        width="30%"
        center
        :show-close="false"
        :before-close="handleClose">
        <!--        <el-button size="small" type="primary" style="margin: 0 80px 5px 80px;"-->
        <!--                   @click="pushWareList">增加库位-->
        <!--        </el-button>-->

        <!--        <div style="display: flex;align-items: center;margin-top: 10px" v-for="(item,index) in addWareList"-->
        <!--             :key="'addWareList'+index">-->
        <div style="display: flex;align-items: center;margin-top: 10px">
          <span>库位列表：</span>
          <el-select v-model="warehousePosition" filterable multiple
                     placeholder="请选择" style="width: 350px;margin-left: 20px" size="small">
            <el-option v-for="item in positionList" :key="item"
                       :value="item"
                       :label="item">
            </el-option>
          </el-select>
          <!--          <el-link style="font-size: 12px;width: 80px"-->
          <!--                   @click="deleteProduce(addWareList,index)">删除-->
          <!--          </el-link>-->
        </div>
        <span slot="footer" class="dialog-footer">
    <el-button @click="openWare = false">取 消</el-button>
    <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="修改预警值"
        :visible.sync="openWarning"
        width="25%"
        center
        :show-close="false"
        :before-close="handleClose">
        <div style="display: flex;align-items: center;margin-top: 10px">
          <span>库存警告值：</span>
          <el-input-number v-model="warningNum" :min="0">
          </el-input-number>
        </div>
        <div style="display: flex;align-items: center;margin-top: 10px">
          <span>紧急补货值：</span>
          <el-input-number v-model="exigencyNum" :min="0">
          </el-input-number>
        </div>
        <span slot="footer" class="dialog-footer">
    <el-button @click="openWarning = false">取 消</el-button>
    <el-button type="primary" @click="submitWarning">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </Table>
</template>

<script>
import { mapState } from "vuex";
import modifyInventory from "./components/modifyInventory.vue";
import tableMixins from "@/mixins/tableMixins.vue";
import * as XLSX from 'xlsx-js-style';

export default {
  name: "InventoryDetail",
  mixins: [tableMixins],
  components: {
    modifyInventory,
  },
  data() {
    return {
      loading: false,
      warehousePosition: [],
      areaList: [],
      componentKey: 0,
      addWareList: [],
      positionList: [],
      apiName: "getInventory",
      openWare: false,
      warningNum: "",
      exigencyNum: "",
      openWarning: false,
      form: {
        productName: {
          tag: "el-input",
          label: "产品名称",
          value: "",
          props: {
            clearable: true,
            placeholder: "请输入产品名称",
          },
        },
        productCode: {
          tag: "el-input",
          label: "产品编码",
          value: "",
          props: {
            clearable: true,
            placeholder: "请输入产品编码",
          },
        },
        // directoryId: this.formDirectoryId(),
        areaId: this.formArea(),
      },
    };
  },
  created() {
    this.$api.areaLedgerAreaList().then(res => {
      this.areaList = res
    })
  },
  computed: {
    ...mapState(["userData"]),
    btnAuth() {
      const { authority = [] } = this.userData || {};
      return authority.includes(192);
    },
    headers() {
      const token = this.token || this.$quinn.getStorage("token");
      return {
        token,
      };
    },
  },
  methods: {
    onBefore(e) {
      this.loading = true;
    },
    onError(e) {
      this.loading = false;
      this.$message("导入失败");
    },
    onSuccess(res) {
      if (res.code != 200) {
        this.$message(res.msg);
      } else {
        this.$message({ message: "导入成功！", type: "success" });
      }
      this.loading = false;
    },
    handleClose() {
      this.openWare = false
    },
    handleAction(opts, row) {
      if (opts === "modifyCount") this.showDialog(opts, row);
      if (opts === "modifyWarePosition") {
        this.$api.inventoryGetLocationName().then(res => {
          this.positionList = res
        })
        this.ids = row.id
        if (row.warehousePosition) {
          this.warehousePosition = row.warehousePosition.split(',')
        } else {
          this.warehousePosition = []
        }
        this.openWare = true
      }
      if (opts === "modifyWarning") {
        this.ids = row.id
        this.areaId = row.area
        this.materialId = row.materialId
        this.openWarning = true
        this.warningNum = row.warningNum
        this.exigencyNum = row.exigencyNum
      }
    },
    submitWarning() {
      if(this.exigencyNum>this.warningNum) return this.$message({message:"紧急补货值不可大于预警值！"})
      const data = {
        warningNum: this.warningNum,
        exigencyNum: this.exigencyNum,
        areaId: this.areaId,
        materialId: this.materialId
      }
      this.$api.inventoryUpdateInventoryWarningNum(data).then(res => {
        if (res == 1) {
          this.$message({ message: "操作成功！", type: "success" })
          this.openWarning = false
          // window.location.reload(true);
          this.componentKey += 1
        }
      })
    },
    async defaultInventory(val) {
      this.$message({ message: "数据量较大，请耐心等候！", type: "warning" })
      try {
        const params = {
          pageSize: 1000000,
          pageNumber: 1,
          areaId: val
        };
        const res = await this.$api.inventoryGetInventoryList(params);
        const downData = res.data;
        function getWarehouse(val) {
          switch (val) {
            case 43:
              return '宁乡壹';
            case 44:
              return '广东仓';
            case 45:
              return '广西仓';
            case 46:
              return '宁乡贰';
            case 52:
              return '贵州仓';
            case 53:
              return '云南仓';
            case 54:
              return '武汉仓';
            default:
              return '未知仓库';
          }
        }
        const data = downData.map(a => ({
          区域: getWarehouse(a.area),
          产品编码: a.productCode,
          产品名称: a.productName,
          规格: a.norms,
          单位: a.unit,
          颜色: a.colour,
          库存: a.count,
        }));
        const sheetName = getWarehouse(val) + '库存明细';
        const wb = XLSX.utils.book_new();
        const sheet = XLSX.utils.json_to_sheet(data);
        sheet['!cols'] = [
          { wpx: 100 }, // 区域
          { wpx: 100 }, // 产品编码
          { wpx: 200 }, // 产品名称
          { wpx: 150 }, // 规格
          { wpx: 100 }, // 单位
          { wpx: 100 }, // 颜色
          { wpx: 100 }  // 库存
        ];
        XLSX.utils.book_append_sheet(wb, sheet, sheetName);
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
        const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `${getWarehouse(val)}库存明细${new Date().getTime()}.xlsx`;
        link.click();
        URL.revokeObjectURL(link.href);
      } catch (error) {
        console.error('Error generating inventory report:', error);
      }
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i < s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xFF;
        }
        return buf;
      }
    },
    // pushWareList() {
    //   this.addWareList = [...this.addWareList, {
    //     warehousePosition: "",
    //   }]
    // },
    // deleteProduce(list, index) {
    //   list.splice(index, 1)
    // },
    submit() {
      const data = {
        warehousePosition: this.warehousePosition,
        id: this.ids
      }
      this.$api.inventoryUpdateLocationName(data).then(res => {
        if (res == 1) {
          this.$message({ message: "操作成功！", type: "success" })
          this.openWare = false
          // window.location.reload(true);
          this.componentKey += 1
        }
      })
    }
  },
};
</script>

<style lang="less" scoped></style>

